// 生产环境API配置文件
// 部署时请将此文件重命名为 api.js 并修改baseUrl为实际的服务器地址

class ApiClient {
    constructor() {
        // 生产环境API地址 - 请根据实际部署情况修改
        // 示例: 'http://your-server-ip:6724/api' 或 'https://your-domain.com/api'
        this.baseUrl = 'http://10.1.200.169:6724/api';  // 实际的API服务器地址
        this.token = localStorage.getItem('authToken');
    }

    // 设置认证令牌
    setToken(token) {
        this.token = token;
        localStorage.setItem('authToken', token);
    }

    // 清除认证令牌
    clearToken() {
        this.token = null;
        localStorage.removeItem('authToken');
    }

    // 获取请求头
    getHeaders() {
        const headers = {
            'Content-Type': 'application/json'
        };
        
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }
        
        return headers;
    }

    // 通用请求方法
    async request(endpoint, options = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        const config = {
            headers: this.getHeaders(),
            ...options
        };

        try {
            const response = await fetch(url, config);
            
            // 检查响应状态
            if (response.status === 401) {
                // 未授权，清除token并跳转到登录页
                this.clearToken();
                window.location.href = '#login';
                throw new Error('未授权访问');
            }
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('API请求错误:', error);
            throw error;
        }
    }

    // GET请求
    async get(endpoint) {
        return this.request(endpoint, {
            method: 'GET'
        });
    }

    // POST请求
    async post(endpoint, data) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    // PUT请求
    async put(endpoint, data) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    // DELETE请求
    async delete(endpoint) {
        return this.request(endpoint, {
            method: 'DELETE'
        });
    }

    // 文件上传
    async uploadFile(endpoint, file, additionalData = {}) {
        const formData = new FormData();
        formData.append('file', file);
        
        // 添加其他数据
        Object.keys(additionalData).forEach(key => {
            formData.append(key, additionalData[key]);
        });

        const headers = {};
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }

        try {
            const response = await fetch(`${this.baseUrl}${endpoint}`, {
                method: 'POST',
                headers: headers,
                body: formData
            });

            if (response.status === 401) {
                this.clearToken();
                window.location.href = '#login';
                throw new Error('未授权访问');
            }

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
            }

            return await response.json();
        } catch (error) {
            console.error('文件上传错误:', error);
            throw error;
        }
    }

    // 认证相关API
    async login(username, password) {
        return this.post('/auth/login', { username, password });
    }

    async logout() {
        try {
            await this.post('/auth/logout');
        } finally {
            this.clearToken();
        }
    }

    // 用户信息
    async getCurrentUser() {
        return this.get('/auth/me');
    }

    // 患者信息API
    async searchPatients(query) {
        return this.get(`/patient/search?query=${encodeURIComponent(query)}`);
    }

    async getPatientById(id) {
        return this.get(`/patient/${id}`);
    }

    // 退款申请API
    async getRefunds(params = {}) {
        const queryString = new URLSearchParams(params).toString();
        return this.get(`/refund${queryString ? '?' + queryString : ''}`);
    }

    async getRefundById(id) {
        return this.get(`/refund/${id}`);
    }

    async createRefund(refundData) {
        return this.post('/refund', refundData);
    }

    async updateRefund(id, refundData) {
        return this.put(`/refund/${id}`, refundData);
    }

    async deleteRefund(id) {
        return this.delete(`/refund/${id}`);
    }

    async auditRefund(id, auditData) {
        return this.post(`/refund/${id}/audit`, auditData);
    }

    // 退款统计API
    async getRefundStatistics(params = {}) {
        const queryString = new URLSearchParams(params).toString();
        return this.get(`/refund/statistics${queryString ? '?' + queryString : ''}`);
    }

    // 附件API
    async uploadAttachment(file, refundId) {
        return this.uploadFile('/file/upload', file, { refundId });
    }

    async deleteAttachment(id) {
        return this.delete(`/file/${id}`);
    }

    async getAttachments(refundId) {
        return this.get(`/file/refund/${refundId}`);
    }

    // 字典API
    async getDictionaries() {
        return this.get('/dict');
    }

    async getDictionaryByType(type) {
        return this.get(`/dict/${type}`);
    }
}

// 创建全局API客户端实例
const apiClient = new ApiClient();

// 导出API客户端（如果使用模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ApiClient;
}